import { request } from '@/api/request';
// import { ShelfCourse } from '@/api/Shelf';
import CusModal from '@/components/CusModal';
import { useReactive } from 'ahooks';
import { App, Button, Drawer, Space, Switch } from 'antd';
import { useRef, useState } from 'react';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
// import { ShelfCourseUpperRef } from '../../../UpperContent';
import { aiStudyApi } from '@/api';
import EditModal from '../../component/EditModal';
import { CourseDetail, CourseDetailProps } from '../Detail';
// type TableRecord = ShelfCourse;
type SearchForm = {
  courseName: string;
};

interface ListPorps {
  // 新增编辑事件
  onAddEdit?(value?: { aiPlanId?: string }): void;
  // 打开弹窗事件
  onDetail?(): Promise<boolean>;
  // 删除事件
  onDelete?(): Promise<boolean>;
}
let editedObj = {};
export function List({ onAddEdit }: ListPorps) {
  const { modal } = App.useApp();
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; type?: string; modelType?: string }>({ show: false });
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  const [tableDep, _reFreshTable] = useState<number>();
  // let [collaKey, setcollaKey] = useState<number>(0);
  // let [adata, setAdata] = useState<any[]>([]);
  const editModalRef = useRef<any>(null);
  const reFreshTable = () => _reFreshTable(Math.random());
  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };
  // 点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    console.log(editModalRef.current, '打印看看这个东西');
    // setTimeout(() => {
    if (editModalRef.current) {
      console.log(editModalRef.current?.onSubmit(), '打印看看咋整');
      editModalRef.current?.onSubmit().then((values: any) => {
        console.log(values, '打印一下下');
        if (values) {
          console.log(values, '打印看看返回的');
          // adata.forEach((el: any, index1: any) => {
          //   if (index1 == values.record.parIndex) {
          //     el.aiStudyTriggerVoList.forEach((item: any, index2: any) => {
          //       if (index2 == values.record.index) {
          //         item.parentClassName = values.record.parentClassName;
          //         item.className = values.record.className;
          //         item.classId = values.record.classId;
          //       }
          //     });
          //   }
          // });
          let params: any = {};
          params = Object.assign({}, editedObj);
          // setColldata();
          params.aiStudyRuleDtoList = [...values.seledData];

          params.aiStudyRuleDtoList.forEach((item: any) => {
            if (item.aiStudyTriggerVoList) item.aiStudyTriggerDtoList = [...item.aiStudyTriggerVoList];
            item.aiStudyTriggerDtoList?.forEach((el: any) => {
              delete el.index;
              delete el.isLast;
              delete el.parIndex;
            });
            delete item.aiStudyTriggerVoList;
          });
          aiStudyApi.addAiPlanTask(params).then((res: any) => {
            console.log(res);
            if (res.code == 200) {
              aiStudyApi.switchStatus({ aiPlanId: res.data, openStatus: 1 }).then((respon: any) => {
                closeModal();
                reFreshTable();
              });
            }
          });
          // getObjPersonNum(values);

          // setAdata([]);
          // setcollaKey(++collaKey);
          // console.log(adata, '到没到这里');
        }
      });
      // .finally(() => {
      //   setModalBtnStatus({ disabled: false, loading: false });
      // });
      setModalBtnStatus({ disabled: false, loading: false });
    }
    // }, 2000);
  };
  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 730,
    centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        确定
      </Button>,
    ],
    onCancel: closeModal,
  };
  const selFirmCont = (param: any) => {
    const { type } = param;
    console.log(param, '打印看看选择的参数');
    // setModalType('matter');
    setIsModalShow({ show: true, type, modelType: 'aaaa' });
    setConfigModal({
      title: '开启AI学习计划',
      children: <EditModal ref={editModalRef} {...param} />,
    });
  };
  const switchStatus = (value: any, record: any) => {
    console.log(value, record, '打印看看当前记录');
    if (!value) {
      modal.confirm({
        title: '关闭AI学习计划',
        // content: `确定删除【${record.name}】吗`,
        content: '关闭后今天任务依然生效，明天将停止该AI学习计划，是否确认关闭?',
        async onOk() {
          await aiStudyApi.switchStatus({ openStatus: 0, aiPlanId: record.aiPlanId });
          reFreshTable();
        },
      });
    } else {
      aiStudyApi.getAiDetail({ aiPlanId: record.aiPlanId }).then((res: any) => {
        const resdata = res.data;
        console.log(res.data, '打印看看详情');
        let hasNoPackage = false;
        resdata.aiStudyRuleVoList.forEach((el: any, index1: any) => {
          el.aiStudyTriggerVoList.forEach((obj: any, index2: any) => {
            if (obj.havePackage == 0) hasNoPackage = true;
            obj.index = index2;
            // obj.isLast = index2 + 1 === el.aiStudyTriggerVoList.length ? 1 : 0;
            obj.parIndex = index1;
          });
        });
        if (hasNoPackage) {
          editedObj = Object.assign({}, res.data);

          // setAdata(resdata.aiStudyRuleVoList);
          // adata = [...resdata.aiStudyRuleVoList];
          selFirmCont({ type: 'add', data: resdata.aiStudyRuleVoList });
        } else {
          aiStudyApi.switchStatus({ openStatus: 1, aiPlanId: record.aiPlanId }).then((res: any) => {
            reFreshTable();
          });
        }
      });
    }
  };
  const detailsPorps = useReactive<{ props?: CourseDetailProps }>({});
  const [columns] = useState<YmColumnsType<any>>([
    {
      title: '计划名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
    },
    {
      title: '学习对象',
      dataIndex: 'studyObject',
      key: 'studyObject',
      width: 200,
      render(value, record) {
        return value == 1 ? <span>协会</span> : value === 2 ? <span>企业</span> : <span>--</span>;
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'openStatus',
      key: 'openStatus',
      width: 80,
      render(value, record) {
        return (
          <Switch
            checked={value}
            onChange={(e) => {
              switchStatus(e, record);
            }}
          ></Switch>
        );
      },
    },
    // operate里不能按钮置灰，只能禁用。所以写这里
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (text, record) => {
        return (
          <Space direction="horizontal" size={0}>
            <Button
              type="text"
              size="small"
              onClick={(e: React.MouseEvent) => {
                e.stopPropagation();
                detailsPorps.props = {
                  aiPlanId: record.aiPlanId,
                  title: record.title,
                  studyObject: record.studyObject,
                };
              }}
            >
              <span className="safe-edu_table_operation_text">详情</span>
            </Button>
            <Button
              type="text"
              size="small"
              onClick={(e: React.MouseEvent) => {
                e.stopPropagation();
                onAddEdit?.({
                  aiPlanId: record.aiPlanId,
                  // cover: record.cover,
                  // courseName: record.name,
                  // learnEndTime: record.learnEndTime,
                  // learnStartTime: record.learnStartTime,
                });
              }}
            >
              <span className="safe-edu_table_operation_text">编辑</span>
            </Button>
            <Button
              type="text"
              size="small"
              disabled={!!record.openStatus}
              onClick={(e: React.MouseEvent) => {
                e.stopPropagation();
                if (record.openStatus == 1) return false; // 开启的不能删除
                modal.confirm({
                  title: '删除AI学习计划',
                  // content: `确定删除【${record.name}】吗`,
                  content: '确认删除该AI学习计划吗?',
                  async onOk() {
                    await aiStudyApi.delAiPlan({ aiPlanId: record.aiPlanId });
                    reFreshTable();
                  },
                });
              }}
            >
              <span className="safe-edu_table_operation_text">删除</span>
            </Button>
          </Space>
        );
      },
    },
  ]);

  // const upperExtram = useReactive<{ guid?: string }>({ guid: undefined });
  // const upperRef = useRef<ShelfCourseUpperRef>(null);

  return (
    <div className="safe_boss_page" style={{ overflowX: 'hidden' }}>
      <YmTable<any, SearchForm>
        searchForm={{
          formItems: [
            {
              label: '名称',
              name: 'title',
              valueType: {
                type: 'input',
              },
            },
          ],
          span: 6,
        }}
        columns={columns}
        request={async ({ page }, form) => {
          const { data } = await request<{ list: any[]; total: number }>({
            url: '/safe/api/aiPlanTask/list',
            data: {
              ...page,
              ...form,
            },
          });

          // console.log('请求发出去了么');
          // const { current = 1, pageSize = 10 } = page ?? {};
          // const data = await ShelfCourse.unShelfList(current, pageSize, form);
          console.log(data, '---再次检查结果');
          return data;
        }}
        requestOptions={{
          reFreshDep: [tableDep],
          defaultPageSize: 20,
        }}
        toolBar={{
          prefixNode: (
            <Button
              type="primary"
              onClick={() => {
                onAddEdit?.();
              }}
            >
              新增
            </Button>
          ),
        }}
        operate={[]}
        rowKey="guid"
      />
      {/* <Modal
        title="上架"
        open={Boolean(upperExtram.guid)}
        onCancel={() => (upperExtram.guid = undefined)}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={async () => {
          const result = await upperRef.current?.submit();
          await ShelfCourse.shelf.upper({ ...upperExtram, ...result });
          upperExtram.guid = undefined;
          reFreshTable();
        }}
      >
        <ShelfUpperModalContentForCourse ref={upperRef}></ShelfUpperModalContentForCourse>
      </Modal> */}
      <Drawer
        width={800}
        open={Boolean(detailsPorps.props)}
        title="计划详情"
        onClose={() => {
          detailsPorps.props = undefined;
        }}
        destroyOnClose
      >
        <CourseDetail {...detailsPorps.props} />
      </Drawer>
      <CusModal {...modalConst} {...configModal} />
    </div>
  );
}
